package com.onenine.app.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.onenine.app.R;
import com.onenine.app.event.AppUpdateEvent;
import com.onenine.app.event.ImageTransitionEvent;
import com.onenine.app.event.MessageNotifyEvent;
import com.onenine.app.event.TabStyleEvent;
import com.onenine.app.fragment.CommunityFragment;
import com.onenine.app.fragment.DiscoveryFragment;
import com.onenine.app.fragment.GameCenterFragment;
import com.onenine.app.fragment.MessageFragment;
import com.onenine.app.fragment.MineFragment;
import com.onenine.app.listener.NetStateChangeObserver;
import com.onenine.app.listener.NetStateChangeReceiver;
import com.onenine.app.utils.CDataProcessor;
import com.onenine.app.utils.DataType;
import com.onenine.app.utils.RoleResLoader;
import com.onenine.app.utils.SpCommonHelper;
import com.onenine.base.base.BaseActivity;
import com.onenine.base.base.BaseEventActivity;
import com.onenine.base.base.BasePageListActivity;
import com.onenine.base.utils.AppConfig;
import com.onenine.base.utils.Toasty;
import com.onenine.base.view.PullRefreshRecyclerView;
import com.onenine.chat.rongcloud.RcUser;
import com.onenine.common.util.ActivityUtils;
import com.onenine.common.util.Logger;
import com.onenine.common.util.NetworkUtils;
import com.umeng.share.UMLogin;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import cn.jzvd.Jzvd;

public class MainActivity extends BaseEventActivity implements TabLayout.OnTabSelectedListener
        , NetStateChangeObserver {

    private final int INIT_INDEX = 2;//首次索引位置
    private final Fragment[] mTabFragment = {new GameCenterFragment()
            , new CommunityFragment(), new DiscoveryFragment(), new MessageFragment(), new MineFragment()};
    private String[] mTabText;
    private int[] mTabIcon;
    private TabLayout mBottomNavigation;
    private View mContainer, mMsgBubble, mVersionBubble;

    @Override
    protected int getLayout() {
        return R.layout.activity_main;
    }

    @Override
    protected void initViews() {
        super.initViews();
        initRoleThemeColor();
        initFragments();
        initBottomTabs();
    }

    @Override
    protected void initListeners() {
        super.initListeners();
        mBottomNavigation.addOnTabSelectedListener(this);
        CDataProcessor.setReceivedCallListener();
        NetStateChangeReceiver.registerObserver(this);
    }

    @Override
    protected void initData() {
        super.initData();
        CDataProcessor.startUploadLocation();
        CDataProcessor.connectRCServer();
        CDataProcessor.syncUserInfo();
        CDataProcessor.syncFriendIds();
        CDataProcessor.checkSyncUserPkId();
        CDataProcessor.syncChatGifts(null);
        CDataProcessor.syncGameCategory(null);
        CDataProcessor.syncCoteries(null);
        CDataProcessor.checkAppUpdate(this, false, false);
    }

    /**
     * 设置角色主题颜色
     */
    private void initRoleThemeColor() {
        BaseActivity.sLoadingColor = RoleResLoader
                .getRoleColorResourceId(RoleResLoader.DynamicResName.THEME_COLOR);
        PullRefreshRecyclerView.sLoadingMoreLayoutId = RcUser.getInstance().getSex() == DataType.SEX_MALE
                ? R.layout.layout_load_more_view_male : R.layout.layout_load_more_view_female;
        BasePageListActivity.sColorSchemeResources = new int[]{RoleResLoader
                .getRoleColorResourceId(RoleResLoader.DynamicResName.THEME_COLOR), RoleResLoader
                .getRoleColorResourceId(RoleResLoader.DynamicResName.THEME_COLOR1)};
        mContainer = findViewById(R.id.home_container);
        mTabText = getResources().getStringArray(R.array.main_tab_text);
        mTabIcon = new int[]{RoleResLoader.getRoleDrawableResourceId(RoleResLoader.DynamicResName.MAIN_TAB_GAME)
                , RoleResLoader.getRoleDrawableResourceId(RoleResLoader.DynamicResName.MAIN_TAB_COMMUNITY)
                , RoleResLoader.getRoleDrawableResourceId(RoleResLoader.DynamicResName.MAIN_TAB_FIND)
                , RoleResLoader.getRoleDrawableResourceId(RoleResLoader.DynamicResName.MAIN_TAB_MESSAGE)
                , RoleResLoader.getRoleDrawableResourceId(RoleResLoader.DynamicResName.MAIN_TAB_MINE)};
    }

    /**
     * 初始化fragment
     */
    private void initFragments() {
        mBottomNavigation = findViewById(R.id.bottom_tab_layout);
        FragmentTransaction transition = getSupportFragmentManager().beginTransaction();
        for (Fragment fragment : mTabFragment) {
            transition.add(R.id.home_container, fragment);
        }
        transition.commit();
    }

    /**
     * 显示某个Fragment
     *
     * @param position
     */
    private void showTabFragment(int position) {
        FragmentTransaction transition = getSupportFragmentManager().beginTransaction();
        for (int i = 0; i < mTabFragment.length; i++) {
            View view = mBottomNavigation.getTabAt(i).getCustomView();
            if (i == position) {
                view.setSelected(true);
                transition.show(mTabFragment[i]);
            } else {
                view.setSelected(false);
                transition.hide(mTabFragment[i]);
            }
        }
        transition.commitAllowingStateLoss();
    }

    /**
     * 设置添加Tab
     */
    private void initBottomTabs() {
        final ColorStateList txtColorList = RoleResLoader.getRoleColorStateList(RoleResLoader.DynamicResName.MAIN_TAB_TEXT_COLOR);
        final LayoutInflater layoutInflater = LayoutInflater.from(this);
        for (int i = 0; i < mTabText.length; i++) {
            TabLayout.Tab tab = mBottomNavigation.newTab();
            View view = layoutInflater.inflate(R.layout.layout_tab_item, null, false);
            tab.setCustomView(view);
            TextView tvTitle = view.findViewById(R.id.tv_tab);
            tvTitle.setText(mTabText[i]);
            tvTitle.setTextColor(txtColorList);
            ImageView imgTab = view.findViewById(R.id.iv_tab);
            imgTab.setImageResource(mTabIcon[i]);
            mBottomNavigation.addTab(tab);
        }
        //首次位置
        showTabFragment(INIT_INDEX);
        mBottomNavigation.getTabAt(INIT_INDEX).select();
        //消息红点提醒
        mMsgBubble = mBottomNavigation.getTabAt(3)
                .getCustomView().findViewById(R.id.tv_bubble);
        mMsgBubble.setBackgroundResource(RoleResLoader
                .getRoleDrawableResourceId(RoleResLoader.DynamicResName.CIRCLE_POINT_BUBBLE));
        mVersionBubble = mBottomNavigation.getTabAt(4)
                .getCustomView().findViewById(R.id.tv_bubble);
        mVersionBubble.setBackgroundResource(RoleResLoader
                .getRoleDrawableResourceId(RoleResLoader.DynamicResName.CIRCLE_POINT_BUBBLE));
    }

    /**
     * 在内存吃紧时不保存Fragment状态
     *
     * @param outState
     */
    @SuppressLint("MissingSuperCall")
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        //在内存吃紧时不保存Fragment状态
    }

    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        showTabFragment(tab.getPosition());
        if (isMessageTabSelected()) {
            //清除红点
            setMsgBubbleVisible(false);
        }
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {
    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {
    }

    @Override
    protected void onPause() {
        super.onPause();
        Jzvd.releaseAllVideos();
    }

    @Override
    public void onBackPressed() {
        if (Jzvd.backPress()) {
            return;
        } else if (!AppConfig.isQuickClick2Times()) {
            Toasty.showNormal(R.string.click_back_exit);
        } else {
            ActivityUtils.finishAllActivities(true);
        }
    }

    @Override
    public void onNetDisconnected() {
        Logger.e("网络已断开");
    }

    @Override
    public void onNetConnected(NetworkUtils.NetworkType networkType) {
        Logger.e("网络已连接");
        CDataProcessor.connectRCServer();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MessageNotifyEvent event) {
        if (event.type != DataType.CONNECT_NOTIFY_MSG) {
            if (!isMessageTabSelected()) {
                setMsgBubbleVisible(true);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(TabStyleEvent event) {
        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) mContainer.getLayoutParams();
        if (event.isTransparent) {
            //沉浸式
            lp.removeRule(RelativeLayout.ABOVE);
            mBottomNavigation.setBackgroundColor(Color.TRANSPARENT);
        } else {
            //非沉浸式
            lp.addRule(RelativeLayout.ABOVE, R.id.bottom_tab_layout);
            mBottomNavigation.setBackgroundColor(Color.WHITE);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(AppUpdateEvent event) {
        if (event.updateStatus == DataType.APP_UPDATE) {
            if (!SpCommonHelper.getInstance().isAppVersionMd5Equal(event.newVersionNum)) {
                setVersionBubbleVisible(true);
            }
        } else if (event.updateStatus == DataType.APP_CLEAR_UPDATE) {
            setVersionBubbleVisible(false);
            SpCommonHelper.getInstance().setMd5AppVersion(event.newVersionNum);
        }
    }

    @Override
    public void onActivityReenter(int resultCode, Intent data) {
        if (resultCode == RESULT_OK && data != null) {
            //见BrowserImageActivity的共享视图返回
            ImageTransitionEvent event = new ImageTransitionEvent();
            event.eventName = MainActivity.class.getSimpleName();
            event.position = data.getIntExtra(BrowserImageActivity.IMG_CURRENT_POSITION, -1);
            EventBus.getDefault().post(event);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMLogin.onActivityResult(this, requestCode, resultCode, data);
    }

    private void setMsgBubbleVisible(boolean visible) {
        mMsgBubble.setVisibility(visible ? View.VISIBLE : View.GONE);
    }

    private void setVersionBubbleVisible(boolean visible) {
        mVersionBubble.setVisibility(visible ? View.VISIBLE : View.GONE);
    }

    private boolean isMessageTabSelected() {
        return mBottomNavigation.getSelectedTabPosition() == 3;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        NetStateChangeReceiver.unregisterObserver(this);
    }

}
